/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mol.market.common.network;

import java.io.IOException;
import java.net.HttpURLConnection;

import org.apache.http.HttpStatus;

import android.content.Context;
import android.os.Debug;
import android.support.v4.content.AsyncTaskLoader;

import com.mol.market.Constants;
import com.mol.market.common.util.Utils;

/**
 * 新的API异步访问方式。
 * <p/>
 * Author: Andrew.Wang
 * Date  : 12-9-25
 * Since : Version 0.9.6
 */
public class ApiAsyncTaskLoader extends AsyncTaskLoader<ApiResponse> {

    /**
     * API请求参数
     */
    private ApiRequest mRequest;

    /**
     * API响应结果
     */
    private ApiResponse mResponse;

    private ResponseCacheManager mResponseCache;

    public ApiAsyncTaskLoader(Context context, ApiRequest request) {
        super(context);
        mRequest = request;
    }

    /**
     * Handles a request to start the Loader.
     */
    @Override protected void onStartLoading() {
        if (mResponse != null) {
            // If we currently have a result available, deliver it
            // immediately.
            deliverResult(mResponse);
        }

        if (takeContentChanged() || mResponse == null) {
            // If the data has changed since the last time it was loaded
            // or is not currently available, start a load.
            forceLoad();
        }
    }

    @Override
    public ApiResponse loadInBackground() {

        Object result = null;
        String cacheKey = "";
//        if (ApiRequestFactory.API_CACHE_MAP.contains(mRequest.actionId)) {
//          final boolean isBodyEmpty = (requestEntity == null);
//          if (mRequest.) {
//            // if no http entity then directly use the request url as cache
//            // key
//            cacheKey = Utils.getMD5(mRequest.url);
//          } else {
//            // we only cache string request
//            if (requestEntity instanceof StringEntity) {
//              try {
//                cacheKey = Utils.getMD5(mRequest.url
//                    + EntityUtils.toString((HttpEntity) requestEntity));
//              } catch (ParseException e) {
//                Utils.W("have ParseException when get cache key", e);
//              } catch (IOException e) {
//                Utils.W("have IOException when get cache key", e);
//              }
//            }
//          }
//          // fetch result from the cache
//          result = mResponseCache.getResponse(getContext(), cacheKey);
//          if (result != null) {
//            Utils.V("retrieve response from the cache");
//            return result;
//          }
//        }

        HttpConnectionManager connectionManager = HttpConnectionManager.get(getContext());
        HttpURLConnection connection = null;
        try {

            connection = connectionManager.buildConnection(mRequest);

            Utils.D("request body > " + mRequest.requestBody);

            mResponse = connectionManager.execute(connection, mRequest);

            Utils.D("requestUrl > " + mRequest.url + " statusCode > " + mResponse.status);

            if (HttpStatus.SC_OK != mResponse.status) {
                // 非正常返回
                Utils.D("status code > " + mResponse.status);
                return mResponse;
            }

            // fetch result from remote server
            result = ApiResponseFactory.parse(getContext(), mResponse);
//      if (ApiRequestFactory.API_CACHE_MAP.contains(mRequestAction) && result != null) {
//        mResponseCache.putResponse(mContext, mRequestAction, cacheKey, result);
//      }

            // 处理API Response，如果解析出错，返回BUSSINESS_ERROR【610】
            if (result == null) {
                mResponse = new ApiResponse(mRequest.actionId, ApiResponse.STATUS_LOGIC_ERROR);
            } else {
                mResponse.result = result;
            }
            return mResponse;
        } catch (IOException e) {
            Utils.D("Market API encounter the IO exception[mostly is timeout exception]", e);
            Utils.trackEvent(getContext(), Constants.API_STATUS, Constants.API_TIMEOUT + "->"
                + mRequest.url);
            return mResponse = new ApiResponse(mRequest.actionId,
                ApiResponse.STATUS_LOGIC_ERROR);
        } catch (Exception e) {
            Utils.D("Market API encounter the other exception", e);
            return mResponse = new ApiResponse(mRequest.actionId,
                ApiResponse.STATUS_TIMEOUT_ERROR);
        } finally {
            // release the connection
            if (connection != null) {
                connection.disconnect();
            }

            Utils.D("2 cost cpu time is >>>> " + Debug.threadCpuTimeNanos());
        }
    }

}
